package com.seal.yoyoshop.web;

import com.seal.yoyoshop.bin.Type;
import com.seal.yoyoshop.bin.User;
import com.seal.yoyoshop.service.TypeService;
import com.seal.yoyoshop.service.UserService;
import com.seal.yoyoshop.service.impl.TypeServiceImpl;
import com.seal.yoyoshop.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "RegisterServlet", value = "/index/register")
public class RegisterServlet extends HttpServlet {

    private TypeService typeService = new TypeServiceImpl();
    private UserService userService = new UserServiceImpl();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        显示注册页面
//        导航栏
        request.setAttribute("flag",5);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList",typeList);


        request.getRequestDispatcher("/index/register.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        处理注册逻辑
        //        导航栏
        request.setAttribute("flag", 5);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList", typeList);
        //处理乱码
        request.setCharacterEncoding("UTF-8");
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
//        查询用户是否存在
        User user = userService.getUserByUsername(username);
        if (user == null) {//用户不存在，新建用户
            User newUser = new User(null, username, password, name, phone, address, 1);
            int flag = userService.newUser(newUser);
            if (flag == 1) {
                request.setAttribute("msg", "用户已创建，请登录");
            } else {
                request.setAttribute("msg", "注册信息有误");
            }
        } else {//用户已存在，返回消息并跳转回去
            request.setAttribute("msg", "用户名已存在");

        }
        request.getRequestDispatcher("/index/register.jsp").forward(request, response);
    }
}
